package AttachmentService

import (
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools/fileTypeTest"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gfile"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/guid"
	"github.com/gogf/gf/util/gvalid"
	"strings"
)

// RemotePhoto 上传成功后插入数据
func RemotePhoto(r *ghttp.Request) *response.JsonResponse {
	url := r.GetString("url")
	err := gvalid.CheckValue(r.GetCtx(), url, "required|url", "URL必填|请输入正确的URL")
	if err != nil {
		return response.FailByRequestMessage(r, err.String())
	}
	c := g.Client().GetBytes(url)
	if c == nil {
		return response.FailByRequestMessage(r, "下载文件失败")
	}

	var oneByte int64 = 1048576 // 1MB
	// 默认允许上传5MB
	allowSizeConfig := g.Cfg().GetInt64("upload.AllowSize", 5)
	allowSize := allowSizeConfig * oneByte
	if len(c) > int(allowSize) {
		return response.FailByRequestMessage(r, "文件超过"+gconv.String(allowSizeConfig)+"M")
	}
	filePreFix := g.Cfg().GetString("upload.WwwrootPath")
	saveUrl := "/upload/" + gtime.Now().Format("Ym") + "/" + gtime.Now().Format("d") + "/"
	fileExt := gfile.Ext(url)
	fileMd5 := guid.S()
	fileName := fileMd5 + fileExt
	// 检测文件类型
	allowTypes := g.Cfg().GetStrings("upload.AllowTypes")
	if !fileTypeTest.CheckFileTypeByte(c, allowTypes) {
		return response.FailByRequestMessage(r, "不支持当前类型，只允许上传"+strings.Join(allowTypes, ","))
	}
	// 保存到文件
	saveErr := gfile.PutBytes(filePreFix+saveUrl+fileName, c)
	if saveErr != nil {
		return response.FailByRequestMessage(r, "保存文件失败 "+saveErr.Error())
	}
	// 添加数据到数据库
	insertData := g.Map{
		"original_name": gfile.Basename(url),
		"save_name":     fileName,
		"save_path":     saveUrl,
		"url":           saveUrl + fileName,
		"extension":     strings.Trim(fileExt, "."),
		"mime":          fileTypeTest.GetContentTypeByte(c),
		"size":          len(c),
		"md5":           fileMd5,
	}
	res := UploadAdd(r, insertData)
	if res.Code != 0 {
		return res
	}
	resData := gconv.Map(res.Data)
	insertData["id"] = resData["id"]
	PhotoPreFix := g.Cfg().GetString("upload.PhotoPreFix")
	insertData["base_url"] = PhotoPreFix
	return response.SuccessByRequestMessageData(nil, "成功", insertData)
}
